import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
import { 
  getFromAPI, 
  saveToAPI,
  STORAGE_KEYS,
  getPlansAPI,
  savePlansAPI,
  createPlanAPI,
  updatePlanAPI,
  deletePlanAPI,
  bindContainerToPlanAPI,
  unbindContainerFromPlanAPI,
  getPlanContainersAPI
} from '../utils/storage'

export const usePlanStore = defineStore('plan', () => {
  // 计划数据
  const plans = ref([])
  
  // 异步初始化方法，从 API 加载数据
  async function initFromAPI() {
    try {
      // 使用新的专用接口获取计划数据
      const savedData = await getPlansAPI()
      plans.value = savedData || []
      
      // 确保所有计划ID都是数字类型
      plans.value.forEach(plan => {
        if (plan.id && typeof plan.id === 'string') {
          plan.id = Number(plan.id)
        }
        if (plan.containerIds) {
          plan.containerIds = plan.containerIds.map(id => 
            typeof id === 'string' ? Number(id) : id
          )
        }
      })
    } catch (e) {
      console.warn('加载计划数据失败，使用空数据:', e)
      plans.value = []
    }
  }

  // 创建新计划
  async function createPlan(data) {
    try {
      // 调用 API 创建计划
      // TODO: 后续替换为实际 API 调用 POST ${API_BASE_URL}/plans
      const planId = await createPlanAPI(data)
      
      // 更新本地数据
      const newPlan = {
        id: planId,
        title: data.title,
        description: data.description || '',
        category: data.category || '',
        date: data.date,
        startTime: data.startTime || '',
        endTime: data.endTime || '',
        priority: data.priority || 'medium',
        status: 'pending',
        containerIds: [],
        color: data.color || '#409EFF',
        createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        updatedAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
      }
      plans.value.push(newPlan)
      
      return planId
    } catch (error) {
      console.error('创建计划失败:', error)
      throw error
    }
  }

  // 更新计划
  async function updatePlan(id, data) {
    try {
      // 调用 API 更新计划
      // TODO: 后续替换为实际 API 调用 PUT ${API_BASE_URL}/plans/${id}
      await updatePlanAPI(id, data)
      
      // 更新本地数据
      const plan = plans.value.find(p => p.id === id)
      if (plan) {
        Object.assign(plan, data)
        plan.updatedAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
      }
    } catch (error) {
      console.error('更新计划失败:', error)
      throw error
    }
  }

  // 删除计划
  async function deletePlan(id) {
    try {
      // 调用 API 删除计划
      // TODO: 后续替换为实际 API 调用 DELETE ${API_BASE_URL}/plans/${id}
      await deletePlanAPI(id)
      
      // 更新本地数据
      const index = plans.value.findIndex(p => p.id === id)
      if (index > -1) {
        plans.value.splice(index, 1)
      }
    } catch (error) {
      console.error('删除计划失败:', error)
      throw error
    }
  }

  // 为计划绑定容器
  async function bindContainer(planId, containerId) {
    try {
      // 调用 API 绑定容器
      // TODO: 后续替换为实际 API 调用 POST ${API_BASE_URL}/plans/${planId}/containers
      await bindContainerToPlanAPI(planId, containerId)
      
      // 更新本地数据
      const plan = plans.value.find(p => p.id === planId)
      if (plan && !plan.containerIds.includes(containerId)) {
        plan.containerIds.push(containerId)
        plan.updatedAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
      }
    } catch (error) {
      console.error('绑定容器失败:', error)
      throw error
    }
  }

  // 解绑容器
  async function unbindContainer(planId, containerId) {
    try {
      // 调用 API 解绑容器
      // TODO: 后续替换为实际 API 调用 DELETE ${API_BASE_URL}/plans/${planId}/containers/${containerId}
      await unbindContainerFromPlanAPI(planId, containerId)
      
      // 更新本地数据
      const plan = plans.value.find(p => p.id === planId)
      if (plan) {
        const index = plan.containerIds.indexOf(containerId)
        if (index > -1) {
          plan.containerIds.splice(index, 1)
          plan.updatedAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
      }
    } catch (error) {
      console.error('解绑容器失败:', error)
      throw error
    }
  }

  // 根据日期获取计划
  function getPlansByDate(date) {
    return plans.value.filter(plan => plan.date === date)
  }

  // 获取指定日期范围内的计划
  function getPlansByDateRange(startDate, endDate) {
    return plans.value.filter(plan => {
      const planDate = dayjs(plan.date)
      return planDate.isBetween(startDate, endDate, 'day', '[]')
    })
  }

  // 根据状态获取计划
  function getPlansByStatus(status) {
    return plans.value.filter(plan => plan.status === status)
  }

  // 获取某个计划的绑定容器（直接调用API）
  async function getPlanContainers(planId) {
    try {
      // 调用 API 获取计划绑定的容器列表
      // API 接口：GET ${API_BASE_URL}/plans/${planId}/containers
      const containers = await getPlanContainersAPI(planId)
      return containers || []
    } catch (error) {
      console.error('获取计划容器列表失败:', error)
      return []
    }
  }

  // 获取某个计划的绑定容器（需要配合containerStore使用，保留兼容性）
  function getPlanContainersLocal(planId, containers) {
    const plan = plans.value.find(p => p.id === planId)
    if (!plan || !containers) return []
    
    return containers.filter(container => 
      plan.containerIds.includes(container.id)
    )
  }

  // 保存计划数据到API（暂时保留，用于直接批量保存）
  async function savePlans() {
    try {
      // 使用新的专用接口保存计划数据
      // TODO: 后续可能需要替换为批量更新 API
      // API 接口设计：PUT ${API_BASE_URL}/plans/batch
      await savePlansAPI(plans.value)
    } catch (error) {
      console.error('保存计划数据失败:', error)
    }
  }

  // 今日计划
  const todayPlans = computed(() => {
    const today = dayjs().format('YYYY-MM-DD')
    return getPlansByDate(today)
  })

  // 本周计划
  const weekPlans = computed(() => {
    const startOfWeek = dayjs().startOf('week')
    const endOfWeek = dayjs().endOf('week')
    return getPlansByDateRange(startOfWeek, endOfWeek)
  })

  // 计划统计
  const planStats = computed(() => {
    const total = plans.value.length
    const completed = plans.value.filter(p => p.status === 'completed').length
    const pending = plans.value.filter(p => p.status === 'pending').length
    const inProgress = plans.value.filter(p => p.status === 'in-progress').length
    
    return {
      total,
      completed,
      pending,
      inProgress,
      completionRate: total > 0 ? Math.round((completed / total) * 100) : 0
    }
  })

  return {
    plans,
    todayPlans,
    weekPlans,
    planStats,
    createPlan,
    updatePlan,
    deletePlan,
    bindContainer,
    unbindContainer,
    getPlansByDate,
    getPlansByDateRange,
    getPlansByStatus,
    getPlanContainers,
    getPlanContainersLocal,
    initFromAPI,
    savePlans
  }
})